//
//  PxHomeViewController.m
//  OilCard
//
//  Created by Xu Yefeng on 14-5-18.
//  Copyright (c) 2014年 Free. All rights reserved.
//

#import "PxNotifyFaildListViewController.h"

@implementation PxNotifyFaildListViewController {
    BOOL isLoading;
    BOOL isSelected;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        isSelected = NO;
        isLoading = NO;
        _pageNum = @"1";
        _pageSize = @"15";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // for test
//    self.dataSource = [NSMutableArray new];
//    for (int i=0; i<40; i++) {
//        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"content", @"content",
//                             @"phone", @"phone",
//                             @"id", @"id",
//                             nil];
//        [self.dataSource addObject:dic];
//    }
    // Do any additional setup after loading the view.
    [self setLogoTitleViewWithTitle:@"通知失败"];
    CGFloat height = CGRectGetHeight(self.view.bounds);
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    CGFloat tableHeight = height - [PxGlobal getCustomerHeight:40] - 64;
    if (self.dataSource.count*45 < tableHeight)
        tableHeight = self.dataSource.count*45;
    self.tableView.height = tableHeight;
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorColor = [UIColor colorWithHTMLStr:@"d0d0d0"];
    self.tableView.allowsMultipleSelection = YES;
    
    [self setRightBtn:isSelected];
    [self setBottomBtn];
}

-(void)setRightBtn:(BOOL) isAllSelected
{
    UIButton *navBarRightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 44)];
    [navBarRightButton addTarget:self action:@selector(navBarRightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [navBarRightButton setContentMode:UIViewContentModeCenter];
    
    if (isAllSelected)
        [navBarRightButton setTitle:@"取消"];
    else
        [navBarRightButton setTitle:@"全选"];
    
    navBarRightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    UIColor *color1 = [UIColor colorWithHTMLStr:@"ff4e08"];
    [navBarRightButton setTitleColor:color1 forState:UIControlStateNormal];
    
    UIBarButtonItem *rightButtonItem=[[UIBarButtonItem alloc] initWithCustomView:navBarRightButton];
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    if([LLYTSmallUtil iOSBigVersion] >= 6.5)
        negativeSpacer.width = -9;// it was -6 in iOS 6
    else
        negativeSpacer.width = 1;
    
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:negativeSpacer,rightButtonItem/*this will be the button which u actually need*/, nil] animated:NO];
}

-(void)setBottomBtn
{
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat height = [PxGlobal getCustomerHeight:40];
    CGFloat width = CGRectGetWidth(self.view.frame)/2;
    btn2.frame = CGRectMake(0, CGRectGetHeight(self.view.frame) - height - [PxGlobal getBaseHeight:NO], width, height);
    [btn2 setSelector:@selector(notify) withTarget:self];
    [btn2 setTitle:@"重发短信"];
    [btn2 setTitleColor:[UIColor colorWithHTMLStr:@"ffffff"] forState:UIControlStateNormal];
    btn2.titleLabel.font = [UIFont systemFontOfSize:18];
    btn2.backgroundColor = [UIColor colorWithHTMLStr:@"ff4e08"];
    [self.view addSubview:btn2];
    
    UIButton *btn = [PxGlobal duplicate:btn2];
    [btn setSelector:@selector(delete) withTarget:self];
    btn.left = btn.right;
    btn.backgroundColor = [UIColor colorWithHTMLStr:@"d34108"];
    [btn setTitle:@"删除"];
    [self.view addSubview:btn];
}

-(NSString *)getSelectedGuids
{
    NSString *guids = @"";
    NSArray *arrays = [self.tableView indexPathsForSelectedRows];
    for (NSIndexPath *indexPath in arrays) {
        NSDictionary *dic = self.dataSource[indexPath.row];
        guids = [NSString stringWithFormat:@"%@,%@", guids, dic[@"id"]];
    }
    return [guids substringFromIndex:1];
}

-(void)delete
{
    NSString *guids = [self getSelectedGuids];
    if (guids.length == 0)
        return;
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    cmd.functionName = TRANS_SMS_DEL;
    
    [cmd.paramDic addEntriesFromDictionary:@{@"ids":guids
                                             }];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
        [LLAlertService alertWithTip:@"删除成功"];
        [self getData:EGORefreshHeader];
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        
        [LLAlertService sysAlertWithTip:dic[RESULT_DESC] withTitle:@"错误"];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    
    [LLRestEngine sendCommandRequest:cmd];
}

-(void)notify
{
    NSString *guids = [self getSelectedGuids];
    if (guids.length == 0)
        return;
    
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    cmd.functionName = TRANS_SMS_RESEND;
    
    [cmd.paramDic addEntriesFromDictionary:@{@"ids":guids
                                             }];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
        [LLAlertService alertWithTip:@"通知已发送"];
        [self popToLastControllerWithIncomingParam:nil];
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        
        [LLAlertService sysAlertWithTip:dic[RESULT_DESC] withTitle:@"错误"];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    
    [LLRestEngine sendCommandRequest:cmd];
}

- (void)navBarRightBtnAction
{
    isSelected = !isSelected;
    [self setRightBtn:isSelected];
    for (int row=0; row<self.dataSource.count; row++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
        if (isSelected)
            [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        else
            [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
        [self clickCell:indexPath];
    }
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self getData:EGORefreshHeader];
}

-(void)clickCell:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if(cell.isSelected) {
        cell.imageView.image = [UIImage imageNamed:@"Images/icon-Choose"];
    } else {
        cell.imageView.image = [UIImage imageNamed:@"Images/icon-umChoose"];
    }
}

-(void)buttonClick
{
    // empty
}

#pragma mark tableview delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataSource[indexPath.row];
    static NSString *cellIdentifier = @"cellIdentifier";
    PxSwipeableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[PxSwipeableCell alloc] initWithStyle:UITableViewCellStyleValue1
                                          reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.imageView.image = [UIImage imageNamed:@"Images/icon-umChoose"];
        cell.textLabel.text = dic[@"phone"];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.textColor = [UIColor colorWithHTMLStr:@"4c4c4c"];
        cell.detailTextLabel.text = dic[@"content"];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:10];
        cell.detailTextLabel.textColor = [UIColor colorWithHTMLStr:@"9c9c9c"];
        cell.delegate = self;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self clickCell:indexPath];
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self clickCell:indexPath];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *phoneNo = self.dataSource[indexPath.row][@"phone"];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"拨打 %@",phoneNo] preferredStyle: UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
        NSString *strPhone = [NSString stringWithFormat:@"tel://%@", phoneNo];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strPhone]];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:OKAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getData:(EGORefreshPos)aRefreshPos
{
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    cmd.functionName = TRANS_SMS_FAILD;
    
    [cmd.paramDic addEntriesFromDictionary:@{@"pageSize":_pageSize,
                                             @"pageNo":_pageNum}];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
        NSMutableArray *data = dic[RESULT_DATA];
        self.dataSource = data;
        isLoading = NO;
        
        if ([self.dataSource isKindOfClass:[NSString class]]) {
            self.dataSource = [NSMutableArray array];
        }
        [self.tableView reloadData];
//        [self.tableView refreshDone:aRefreshPos];
//        if (![LLYTSmallUtil hasNextPage:data]) {
//            [self.tableView setFootViewEnable:NO];
//        }
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        [LLAlertService sysAlertWithTip:dic[RESULT_DESC] withTitle:@"错误"];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    
    [LLRestEngine sendCommandRequest:cmd];
}

@end
